<template>
  <div class="article-list">
    <van-pull-refresh
      v-model="refreshing"
      @refresh="onRefresh"
      :success-text="successText"
      :success-duration="1500"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <article-item
          v-for="(item, index) in list"
          :key="index"
          :article="item"
        />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/article'
import ArticleItem from '@/components/article-item'
export default {
  name: 'ActicleList',
  components: {
    ArticleItem
  },
  props: {
    item: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      list: [], // 存储列表数据的数组
      loading: false, // 控制加载中国的 loading 状态
      finished: false, // 控制数据加载结束状态
      timestamp: null, // 用于请求获取下一页的时间戳
      error: false,
      refreshing: false,
      successText: ''
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    async onLoad() {
      try {
        const { data } = await getArticles({
          channel_id: this.item.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1
        })
        // 2.请求结果放入 list 数组中
        const { results } = data.data
        this.list.push(...results)
        // 3.把加载状态设置为结束
        this.loading = false
        // 4.判断数据是否加载完成
        if (results.length) {
          // 更新下一页的时间戳
          this.timestamp = data.data.pre_timestamp
        } else {
          // 没看数据，将 finished 设置为 true
          this.finished = true
        }
      } catch (error) {
        // 展示错误状态
        this.error = true
        // 关闭 loading
        this.loading = false
      }
    },
    // 下拉刷新事件
    async onRefresh() {
      try {
        // 请求获取数据 timestamp 取 Date.now() 最新数据
        const { data } = await getArticles({
          channel_id: this.item.id,
          timestamp: Date.now(),
          with_top: 1
        })
        // 2.追加数据到列表顶部
        const { results } = data.data
        this.list.unshift(...results)
        // 3.关闭下拉刷新的 loading 状态
        this.refreshing = false
        // 更新下拉刷新成功的文字
        this.successText = `刷新成功，更新了${results.length}条 数据`
      } catch (error) {
        this.successText = '刷新失败'
        this.refreshing = false
      }
    }
  }
}
</script>

<style scoped lang="less">
.article-list {
  height: 79vh;
  overflow-y: auto;
}
</style>
